package cn.kzgg.org.service.impl;

import cn.kzgg.basic.service.impl.BaseServiceImpl;
import cn.kzgg.org.domain.Department;
import cn.kzgg.org.mapper.DepartmentMapper;
import cn.kzgg.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    public void save(Department department){
        departmentMapper.save(department);
        this.update(department);


    }

    /**
     * 修改上级层级id
     * @param department
     */
    @Override
    public void update(Department department){
        //定义上级层级
        String dirPath="";
        //如果没有父级层级
        if(department.getParent()==null){
            //说明是顶级
            dirPath="/"+department.getId();
        }else {
            //获取父级
            Department parent = departmentMapper.loadById(department.getParent().getId());
            //获取父级层级
            dirPath=parent.getDirPath()+"/"+department.getId();
        }
        //设置上级层级id
        department.setDirPath(dirPath);
        departmentMapper.update(department);
    }


    /**
     * 无限极树
     * 1.一次性查询出所有数据，放到内存 all
     * 2.从所有数据中找出第一层级 firstCourseType   我们需要返回的最外数据
     * 3.只要不是第一层级的，找自己的上级，并将自己放入上级的children中
     * @return
     */
    @Override
    public List<Department> queryTree() {
        //1.一次性查询出所有数据，放到内存 all
        List<Department> departments = departmentMapper.loadAll();
        //为了找到父亲，把整体部门数据转换成Map<id,deparent>
        Map<Long, Department> allDepts = departments.stream().collect(Collectors.toMap(Department::getId, dept -> dept));
        /*HashMap<Long, Department> allDepts = new HashMap<>();
        for (Department department : departments) {
            //循环绑定
            allDepts.put(department.getId(),department);
        }*/
        //所有部门中找顶级部门
        List<Department> firstDepts = new ArrayList<>();
        for (Department temp : departments) {
            //没有父亲就说明是最大的
            if(temp.getParent_id()==null){
                //2.从所有数据中找出第一层firstDepts
                firstDepts.add(temp);
            }else {
                //3.如果不是第一层，找到上级并将自己放入上层children中
                Department parent = allDepts.get(temp.getParent_id());
                if(parent!=null){
                    parent.getChildren().add(temp);

                }
            }
        }
        return firstDepts;
    }
}
